package com.aliyun;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.green.model.v20180509.TextScanRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.motu.vertx.module.utility.toolset.Tool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * 阿里云文字检测接口（旧版本）
 */
public class TextSyncScan extends BaseSample {

    private static final Logger logger = LoggerFactory.getLogger("TextSyncScan");
    /**
     * 文字检测（地区不同）
     */
    public static TextCheckResult check(String content, String regionId) throws Exception {
        BaseSample.regionId = regionId;
        return check(content);
    }

    /**
     * 文字检测（密钥不同）
     */
    public static TextCheckResult check(String content, String accessKeyId, String accessKeySecret) throws Exception {
        BaseSample.accessKeyId = accessKeyId;
        BaseSample.accessKeySecret = accessKeySecret;
        return check(content);
    }

    /**
     * 文字检测（地区和密钥都不同）
     */
    public static TextCheckResult check(String content, String regionId, String accessKeyId, String accessKeySecret) throws Exception {
        BaseSample.regionId = regionId;
        BaseSample.accessKeyId = accessKeyId;
        BaseSample.accessKeySecret = accessKeySecret;
        return check(content);
    }

    /**
     * 文字检测（使用BaseSample默认配置信息）
     */
    public static TextCheckResult check(String content) throws Exception {

        IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint(getEndPointName(), regionId, "Green", getDomain());

        IAcsClient client = new DefaultAcsClient(profile);
        TextScanRequest textScanRequest = new TextScanRequest();
        textScanRequest.setAcceptFormat(FormatType.JSON); // 指定API返回格式。
        textScanRequest.setHttpContentType(FormatType.JSON);
        textScanRequest.setMethod(com.aliyuncs.http.MethodType.POST); // 指定请求方法。
        textScanRequest.setEncoding("UTF-8");
        textScanRequest.setRegionId(regionId);
        List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();
        Map<String, Object> task1 = new LinkedHashMap<String, Object>();
        task1.put("dataId", UUID.randomUUID().toString());
        /**
         * 待检测的文本，长度不超过10000个字符。
         */
        task1.put("content", content);
        tasks.add(task1);
        JSONObject data = new JSONObject();

        /**
         * 检测场景。文本垃圾检测请传递antispam。
         **/
        data.put("scenes", Arrays.asList("antispam"));
        data.put("tasks", tasks);
//        System.out.println(JSON.toJSONString(data, true));
        textScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);
        // 请务必设置超时时间。
        textScanRequest.setConnectTimeout(3000);
        textScanRequest.setReadTimeout(6000);
        try {
            HttpResponse httpResponse = client.doAction(textScanRequest);
            if(httpResponse.isSuccess()){
                JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
//                System.out.println(JSON.toJSONString(scrResponse, true));
                if (200 == scrResponse.getInteger("code")) {
                    JSONArray taskResults = scrResponse.getJSONArray("data");
                    for (Object objTask : taskResults) {
                        JSONObject taskResult = (JSONObject)objTask;
                        if(200 == taskResult.getInteger("code")){
                            String filteredContent = taskResult.getString("filteredContent");
                            if (!Tool.isEmpty(filteredContent)){
                                logger.warn("text check warn content:" + content + " filteredContent:" + filteredContent);
                                return new TextCheckResult(false, filteredContent);
                            }
                            JSONArray sceneResults = taskResult.getJSONArray("results");
                            for (Object objScene : sceneResults) {
                                JSONObject sceneResult = (JSONObject)objScene;
//                                String scene = sceneResult.getString("scene");
                                String suggestion = sceneResult.getString("suggestion");
                                if (suggestion.equals("pass")){
                                    return new TextCheckResult(true, null);
                                } else{
                                    logger.warn("text check warn content:" + content);
                                    return new TextCheckResult(false, null);
                                }
                                // 根据scene和suggetion做相关处理。
                                // suggestion == pass表示未命中垃圾。suggestion == block表示命中了垃圾，可以通过label字段查看命中的垃圾分类。
//                                System.out.println("args = [" + scene + "]");
//                                System.out.println("args = [" + suggestion + "]");
                            }
                        }else{
                            logger.error("text check fail task code:" + ((JSONObject)taskResult).getInteger("code") + " content:" + content);
                        }
                    }
                } else {
                    logger.error("text check fail response code:" + scrResponse.getInteger("code") + " content:" + content);
                }
            }else{
                logger.error("text check fail response not success status:" + httpResponse.getStatus() + " content:" + content);
            }
        }  catch (Exception e) {
            logger.error("text check fail exception:" + Tool.getException(e) + " content:" + content);
        }
        return new TextCheckResult(true, null);// 如果是检测服务器异常，那么本次检测也通过，不会影响到游戏业务
    }

    public static void main(String[] args) throws Exception {

        IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint(getEndPointName(), regionId, "Green", getDomain());

        IAcsClient client = new DefaultAcsClient(profile);
        TextScanRequest textScanRequest = new TextScanRequest();
        textScanRequest.setAcceptFormat(FormatType.JSON); // 指定API返回格式。
        textScanRequest.setHttpContentType(FormatType.JSON);
        textScanRequest.setMethod(com.aliyuncs.http.MethodType.POST); // 指定请求方法。
        textScanRequest.setEncoding("UTF-8");
        textScanRequest.setRegionId(regionId);
        List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();
        Map<String, Object> task1 = new LinkedHashMap<String, Object>();
        task1.put("dataId", UUID.randomUUID().toString());
        /**
         * 待检测的文本，长度不超过10000个字符。
         */
//        task1.put("content", "毛*泽*东");
//        task1.put("content", "刁*进*平*吓台专政");
        task1.put("content", "囍*进*瓶");
//        task1.put("content", "加QQ123456");
        tasks.add(task1);
        JSONObject data = new JSONObject();

        /**
         * 检测场景。文本垃圾检测请传递antispam。
         **/
        data.put("scenes", Arrays.asList("antispam"));
        data.put("tasks", tasks);
        System.out.println(JSON.toJSONString(data, true));
        textScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);
        // 请务必设置超时时间。
        textScanRequest.setConnectTimeout(3000);
        textScanRequest.setReadTimeout(6000);
        try {
            HttpResponse httpResponse = client.doAction(textScanRequest);
            if(httpResponse.isSuccess()){
                JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
                System.out.println(JSON.toJSONString(scrResponse, true));
                if (200 == scrResponse.getInteger("code")) {
                    JSONArray taskResults = scrResponse.getJSONArray("data");
                    for (Object objTask : taskResults) {
                        JSONObject taskResult = (JSONObject)objTask;
                        if(200 == taskResult.getInteger("code")){
                            JSONArray sceneResults = taskResult.getJSONArray("results");
                            for (Object objScene : sceneResults) {
                                JSONObject sceneResult = (JSONObject)objScene;
                                String scene = sceneResult.getString("scene");
                                String suggestion = sceneResult.getString("suggestion");
                                // 根据scene和suggetion做相关处理。
                                // suggestion == pass表示未命中垃圾。suggestion == block表示命中了垃圾，可以通过label字段查看命中的垃圾分类。
                                System.out.println("args = [" + scene + "]");
                                System.out.println("args = [" + suggestion + "]");
                            }
                            System.out.println(taskResult.getString("filteredContent"));
                        }else{
                            System.out.println("task process fail:" + taskResult.getInteger("code"));
                        }
                    }
                } else {
                    System.out.println("detect not success. code:" + scrResponse.getInteger("code"));
                }
            }else{
                System.out.println("response not success. status:" + httpResponse.getStatus());
            }
        }  catch (Exception e) {
            e.printStackTrace();
        }
    }
}
